package com.mars.boss.weixin.wx.handler;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mars.boss.weixin.entity.WeixinKeyWord;
import com.mars.boss.weixin.service.WeixinService;
import com.mars.boss.weixin.wx.model.NewsMessage;
import com.mars.boss.weixin.wx.model.TextMessage;
import com.mars.boss.weixin.wx.utils.WeixinConstant;
import com.mars.boss.weixin.wx.utils.WeixinMessageUtil;
import com.mars.common.spring.SpringContextHolder;
import com.mars.common.utils.date.DateUtil;

public class WeixinHandler {

	private static Logger logger = LoggerFactory.getLogger(WeixinHandler.class);

	public static String processRequest(HttpServletRequest request) {
		logger.debug("收到微信请求：" + DateUtil.getCurrentDateTimeString());
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = null;
			
			// xml请求解析
			Map<String, String> requestMap = WeixinMessageUtil.parseXml(request);

			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			// 消息内容
			String content = requestMap.get("Content");

			logger.debug("消息类型：" + msgType);
			logger.debug("消息内容：" + content);
			logger.debug("事件类型：" + requestMap.get("Event"));
			logger.debug("消息JSON：" + requestMap);
			
			// 回复文本消息
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(WeixinConstant.RESP_MESSAGE_TYPE_TEXT);

			//服务接口
			WeixinService weixinService = SpringContextHolder.getBean(WeixinService.class) ;
			
			// 文本消息
			if (msgType.equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_TEXT)) {
				respContent = "您发送的是文本消息！" ;
				
				WeixinKeyWord kw = weixinService.getKeyword(content) ;
				if("text".equals(kw.getResponseType())) {
					respContent = kw.getContent() ;
					
				} else if("news".equals(kw.getResponseType())) {
					JSONObject parseObject = JSON.parseObject(kw.getResponseParams()) ;
					NewsMessage newsMessage = weixinService.getNews(Long.parseLong(parseObject.get("categoryId").toString())) ;
					newsMessage.setToUserName(fromUserName);
					newsMessage.setFromUserName(toUserName);
					newsMessage.setCreateTime(new Date().getTime());
					newsMessage.setMsgType(WeixinConstant.RESP_MESSAGE_TYPE_NEWS);
					return WeixinMessageUtil.newsMessageToXml(newsMessage) ;
					
				} else if("video".equals(kw.getResponseType())) {
					respContent = "请求Video数据，暂时不提供...." ;
				}
			}
			// 图片消息
			else if (msgType.equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_IMAGE)) {
				respContent = "您发送的是图片消息！" ;
			}
			// 地理位置消息
			else if (msgType.equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_LOCATION)) {
				respContent = "您发送的是地理位置消息！坐标（X："+requestMap.get("Location_X")+"，Y："+requestMap.get("Location_Y")+"）地址：" + requestMap.get("Label") ;
			}
			// 链接消息
			else if (msgType.equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_LINK)) {
				respContent = "您发送的是链接消息！";
			}
			// 音频消息
			else if (msgType.equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_VOICE)) {
				respContent = "您发送的是音频消息！";
			}
			// 事件推送
			else if (msgType.equalsIgnoreCase(WeixinConstant.REQ_MESSAGE_TYPE_EVENT)) {
				// 事件类型
				String eventType = requestMap.get("Event");
				// 事件KEY值
				String eventKey = requestMap.get("EventKey");
				
				// 自定义菜单点击事件
				if (eventType.equalsIgnoreCase(WeixinConstant.EVENT_TYPE_CLICK)) {
					respContent = weixinService.menuProcess(eventKey) ;
				}
				
				// 扫码推事件
				if (eventType.equalsIgnoreCase(WeixinConstant.EVENT_TYPE_SCANCODE_PUSH)) {
					respContent = "扫码推事件";
				}

				// 扫码推事件且弹出“消息接收中”
				if (eventType.equalsIgnoreCase(WeixinConstant.EVENT_TYPE_SCANCODE_WAITMSG)) {
					respContent = "扫描后返回结果给用户";
				}

				// 订阅
				if (eventType.equalsIgnoreCase(WeixinConstant.EVENT_TYPE_SUBSCRIBE)) {
					respContent = "感谢您的关注！";
				}
				// 取消订阅
				else if (eventType.equalsIgnoreCase(WeixinConstant.EVENT_TYPE_UNSUBSCRIBE)) {
					// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				}
			}
			
			textMessage.setContent(respContent);
			respMessage = WeixinMessageUtil.textMessageToXml(textMessage);

			System.out.println("====================================回复内容===================================");
			System.out.println(respMessage);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return respMessage;
	}

}
